<?php
include 'lib.php';
ini_set('display_errors', 1);
ini_set('maximum_execution', 500);

$ftp_host = "shitforcheap.com";
$ftp_user_name = "store@ediskjockey.com";
$ftp_user_pass = "10oswald";

if ($_GET['id']) $tracks = Database::query("SELECT * FROM `tracks` WHERE `id` = ".$_GET['id']);
else $tracks = Database::query("SELECT * FROM `tracks` WHERE `cdn_domain` IS NULL ORDER BY RAND() LIMIT 1");

$track = $tracks[0];
$file = str_replace(" ", "%20", $track['url']);
echo $file;
$file_contents = file_get_contents($file, FILE_BINARY, null, 0, 15000000);
$track_file = fopen("tmp/".$track['id'].".mp3", "w");
fwrite($track_file, $file_contents);
if (filesize("tmp/".$track['id'].".mp3") > 5000000)
{
	echo shell_exec('lame --mp3input -b 128 "tmp/'.$track['id'].'.mp3" "tmp/'.$track['id'].'_128.mp3"');
	$local_filename = '/var/www/sonicportal/app/webroot/tmp/'.$track['id'].'_128.mp3';
	$remote_file = $track['id'].'_128.mp3';
}
else 
{
	$local_filename = '/var/www/sonicportal/app/webroot/tmp/'.$track['id'].'.mp3';
	$remote_file = $track['id'].'.mp3';
}

// set up basic connection
$conn_id = ftp_connect($ftp_host);
var_dump($track);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// upload a file

if (ftp_put($conn_id, $remote_file, $local_filename, FTP_BINARY)) 
{
    $track['cdn_domain'] = "http://shitforcheap.com";
    $track['cdn_path'] = "/store/".$remote_file;
    Database::save("tracks", $track);
    echo '<h3>saved</h3>';
} else 
{
    echo "There was a problem while uploading $file local: $local_filename remote: $remote_file\n";
}

// close the connection
ftp_close($conn_id);

?>